package com.abc.common.springmvc.velocity;

import com.abc.common.web.url.WebUrl;
import org.apache.velocity.context.Context;
import org.springframework.web.servlet.view.velocity.VelocityLayoutView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * Created by xuexue on 2014/4/13.
 */
public class VelocityToolsMapView extends VelocityLayoutView {
    private Map<String, Object> velocityTools;
    private Map<String, WebUrl> velocityUrl;

    @Override
    protected Context createVelocityContext(
            Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {

        Context context=super.createVelocityContext(model,request,response);
        mergeContext(context);
        return context;
    }

    private void mergeContext(Context context) {
        mergeUrl(context, velocityUrl);
        merge(context, velocityTools);
    }
    private void merge(Context context, Map<String, Object> map) {
        if (map != null) {
            for (Map.Entry<String, Object> stringObjectEntry : map.entrySet()) {
                context.put(stringObjectEntry.getKey(), stringObjectEntry.getValue());
            }
        }
    }
    private void mergeUrl(Context context, Map<String, WebUrl> map) {
        if (map != null) {
            for (Map.Entry<String, WebUrl> stringWebUrlEntry : map.entrySet()) {
                String key = stringWebUrlEntry.getKey();
                WebUrl org = stringWebUrlEntry.getValue();
                WebUrl value = org.clone();//解决多线程并发的问题。
                value.setWebUrl(org); //原始的不拿出来配置。
                context.put(key, value);
            }
        }
    }

    public void setVelocityTools(Map<String, Object> velocityTools) {
        this.velocityTools = velocityTools;
    }

    public void setVelocityUrl(Map<String, WebUrl> velocityUrl) {
        this.velocityUrl = velocityUrl;
    }
}
